package com.partyjoin.project.module.officialEvolve.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.partyjoin.common.constant.Constants;
import com.partyjoin.common.utils.DateUtils;
import com.partyjoin.common.utils.security.ShiroUtils;
import com.partyjoin.framework.aspectj.lang.annotation.Log;
import com.partyjoin.framework.aspectj.lang.constant.BusinessType;
import com.partyjoin.framework.web.controller.BaseController;
import com.partyjoin.framework.web.domain.AjaxResult;
import com.partyjoin.framework.web.page.TableDataInfo;
import com.partyjoin.project.module.conference.domain.Conference;
import com.partyjoin.project.module.conference.service.IConferenceService;
import com.partyjoin.project.module.developmentEvolve.domain.DevelopmentEvolve;
import com.partyjoin.project.module.officialEvolve.domain.OfficialEvolve;
import com.partyjoin.project.module.officialEvolve.service.IOfficialEvolveService;
import com.partyjoin.project.module.proposer.domain.Proposer;
import com.partyjoin.project.module.proposer.service.IProposerService;
import com.partyjoin.project.system.role.domain.Role;
import com.partyjoin.project.system.role.service.IRoleService;
import com.partyjoin.project.system.user.domain.User;
import com.partyjoin.project.system.user.service.IUserService;

/**
 * 发展正式党员记录 信息操作处理
 * 
 * @author 莫东林
 * @date 2018-07-19
 */
@Controller
@RequestMapping("/module/officialEvolve")
public class OfficialEvolveController extends BaseController
{
    private String prefix = "module/officialEvolve";
	
	@Autowired
	private IOfficialEvolveService officialEvolveService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IConferenceService conferenceService;
	@Autowired
	private IProposerService proposerService;
	
	@RequiresPermissions("module:officialEvolve:view")
	@GetMapping()
	public String officialEvolve()
	{
	    return prefix + "/officialEvolve";
	}
	
	/**
	 * 用户上级审核备案时动态获取成员材料
	 * @param userId
	 * @return
	 */
	@PostMapping("/selectUserById")
	@ResponseBody
	public User selectUserById(@RequestParam(name = "userId", required = true) String userId){
		User user = userService.selectProposer(Long.parseLong(userId));
		return user;
	}
	
	/**
	 * 保存备案决议名单
	 */
	@RequiresPermissions("module:officialEvolve:edit")
	@PostMapping("/saveUserList")
	@ResponseBody
	public AjaxResult saveUserList(OfficialEvolve officialEvolve){
		User user = ShiroUtils.getUser();
		//更新预备党员角色变更为正式党员
		String[] userIds = officialEvolve.getSuccessList().split(",");
		Long[] roleIds = {Constants.OFFICIAL_ROLE_ID};
		if(userIds != null && userIds.length > 0 && !userIds[0].equals("")){
			for(String userId : userIds){
				User users = userService.selectUserById(Long.parseLong(userId));
				Proposer update = proposerService.selectProposerById(users.getUserId());
				update.setOfficialTime(DateUtils.getNowDate());
				proposerService.updateProposer(update);
				//销毁预备党员角色
				userService.removeUserRole(Long.parseLong(userId), Constants.PREPARE_ROLE_ID);

				users.setRoleIds(roleIds);
				userService.insertUserRole(users);
			}
		}
		officialEvolve.setDisposeTime(DateUtils.getNowDate());
		officialEvolve.setState(1);
		officialEvolve.setUpdateBy(user.getUserName());
		officialEvolve.setUpdateTime(DateUtils.getNowDate());
		if(officialEvolveService.updateOfficialEvolve(officialEvolve) > 0){
			Conference c = conferenceService.selectConferenceById(officialEvolve.getConferenceId());
			c.setState(2);
			if(conferenceService.updateConference(c) > 0){
				return success();
			}else{
				return error();
			}
		}else{
			return error();
		}
	}
	
	/**
	 * 根据培养记录编号获取备案成员列表
	 */
	@RequiresPermissions("module:officialEvolve:list")
	@PostMapping("getRecordsUserList")
	@ResponseBody
	public TableDataInfo getRecordsUserList(@RequestParam(name = "id") Integer officialEvolveId){
		OfficialEvolve officialEvolve = officialEvolveService.selectOfficialEvolveById(officialEvolveId);
		String[] users = officialEvolve.getPrepareList().split(",");
		List<User> userList = new ArrayList<User>();//存放备案成员
		for(String userId : users){
			User u = userService.selectProposer(Long.parseLong(userId));
			userList.add(u);
		}
		return getDataTable(userList);
	}
	
	/**
	 * 打开备案审核详情界面
	 */
	@RequiresPermissions("module:officialEvolve:edit")
	@GetMapping("/record/details")
	public String recordDetails(OfficialEvolve officialEvolve, Model model){
		officialEvolve = officialEvolveService.selectOfficialEvolveById(officialEvolve.getOfficialEvolveId());
//		List<User> recordUserList = new ArrayList<User>();//存放备案名单
//		List<User> recordPassUserList = new ArrayList<User>();//存放备案通过名单
//		List<User> recordNotPassUserList = new ArrayList<User>();//存放备案未通过名单
//		User u = null;//用于开页展示
//		//获取会议
		Conference c = conferenceService.selectConferenceById(officialEvolve.getConferenceId());
		officialEvolve.setConference(c);
//		if(officialEvolve.getPrepareList() != null){
//			String[] userList = officialEvolve.getPrepareList().split(",");
//			u = userService.selectProposer(Long.parseLong(userList[0]));
//			for(String id : userList){
//				User user = userService.selectUserById(Long.parseLong(id));
//				recordUserList.add(user);
//			}
//		}
//		if(officialEvolve.getSuccessList() != null){
//			String[] passList = officialEvolve.getSuccessList().split(",");
//			for(String id : passList){
//				User user = userService.selectUserById(Long.parseLong(id));
//				recordPassUserList.add(user);
//			}
//		}else{
//			recordPassUserList = null;
//		}
//		if(officialEvolve.getFailList() != null){
//			String[] notPassList = officialEvolve.getFailList().split(",");
//			for(String id : notPassList){
//				User user = userService.selectUserById(Long.parseLong(id));
//				recordNotPassUserList.add(user);
//			}
//		}else{
//			recordNotPassUserList = null;
//		}
//		model.addAttribute("user", u);
//		model.addAttribute("recordUserList", recordUserList);
//		model.addAttribute("recordPassUserList", recordPassUserList);
//		model.addAttribute("recordNotPassUserList", recordNotPassUserList);
		model.addAttribute("officialEvolve", officialEvolve);
//		System.out.println(recordPassUserList);
//		System.out.println(recordNotPassUserList);
		return prefix + "/recordDetails_bak";
	}
	
	/**
	 * 上级备案信息列表
	 */
	@RequiresPermissions("module:officialEvolve:list")
	@PostMapping("/record/lists")
	@ResponseBody
	public TableDataInfo recordLists(OfficialEvolve officialEvolve){
		startPage();
		//根据登陆用户查询其部门及其子部门备案记录
		if(officialEvolve.getDeptId() == null){
			officialEvolve.setDeptId(ShiroUtils.getUserDeptId());
		}
		List<OfficialEvolve> list = officialEvolveService.selectOfficialEvolveList(officialEvolve);
		list = idToNameList(list);
		return getDataTable(list);
	}
	
	/**
	 * 打开上级备案管理界面
	 */
	@RequiresPermissions("module:officialEvolve:list")
	@GetMapping("/recordList")
	public String recordList(Model model){
		//获取登陆用户判断管理员角色，若是支部管理员，则无权进行备案操作，只能等待备案
		User user = userService.selectProposer(ShiroUtils.getUserId());
		model.addAttribute("user", user);
		return prefix + "/recordList";
	}
	
	/**
	 * 打开正式党员详情
	 */
	@RequiresPermissions("module:officialEvolve:list")
	@GetMapping("/officialDetails")
	public String officialDetails(User user, Model model){
		user = userService.selectProposer(user.getUserId());
		model.addAttribute("user", user);
		return prefix + "/officialDetails";
	}
	
	/**
	 * 查询发展正式党员记录列表
	 */
	@RequiresPermissions("module:officialEvolve:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(User user)
	{
		startPage();
		//没部门筛选时,默认根据登录用户所在部门筛选
		if(user.getDeptId() == null){
			user.setDeptId(ShiroUtils.getUserDeptId());
		}
        List<User> list = userService.selectOfficialList(user);
		List<Role> roleList = new ArrayList<Role>();
		for(User u : list){
			roleList = roleService.selectRolesByUserId(u.getUserId());
			int i = 0;
			Long[] roles = new Long[10];
			for(Role role : roleList) {
				if(role.isFlag()){
					roles[i]=role.getRoleId();
					i++;
				}

			}
			u.setRoleIds(roles);
		}
		return getDataTable(list);
	}
	
	/**
	 * 新增发展正式党员记录
	 */
	@RequiresPermissions("module:officialEvolve:add")
	@Log(title = "发展正式党员记录", action = BusinessType.INSERT)
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}

	/**
	 * 修改发展正式党员记录
	 */
	@RequiresPermissions("module:officialEvolve:edit")
	@Log(title = "发展正式党员记录", action = BusinessType.UPDATE)
	@GetMapping("/edit/{officialEvolveId}")
	public String edit(@PathVariable("officialEvolveId") Integer officialEvolveId, Model model)
	{
		OfficialEvolve officialEvolve = officialEvolveService.selectOfficialEvolveById(officialEvolveId);
		model.addAttribute("officialEvolve", officialEvolve);
	    return prefix + "/edit";
	}
	
	/**
	 * 保存发展正式党员记录
	 */
	@RequiresPermissions("module:officialEvolve:save")
	@Log(title = "发展正式党员记录", action = BusinessType.SAVE)
	@PostMapping("/save")
	@ResponseBody
	public AjaxResult save(@RequestParam(value = "file") MultipartFile file, OfficialEvolve officialEvolve)
	{
		User user = ShiroUtils.getUser();
		if(upload(officialEvolve, file, Constants.OFFICIAL_ROSTER)){
			officialEvolve.setOfficialRoster("/" + DateUtils.getDate() + "/" + officialEvolve.getConferenceId() + "/" + file.getOriginalFilename());
		}
		officialEvolve.setState(0);
		officialEvolve.setSubmitTime(DateUtils.getNowDate());
		officialEvolve.setCreateBy(user.getUserName());
		officialEvolve.setDeptId(ShiroUtils.getUserDeptId());
		officialEvolve.setCreateTime(DateUtils.getNowDate());
		System.out.println(officialEvolve);
		if (officialEvolveService.insertOfficialEvolve(officialEvolve) > 0)
		{
			//会议与发展记录id互绑
			Conference conference = conferenceService.selectConferenceById(officialEvolve.getConferenceId());
			conference.setState(1);
			if(conferenceService.saveConference(conference) > 0){
				return success();
			}
		}
		return error();
	}
	/**
	 * 删除发展正式党员记录
	 */
	@RequiresPermissions("module:officialEvolve:remove")
	@Log(title = "发展正式党员记录", action = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		int rows = officialEvolveService.deleteOfficialEvolveByIds(ids);
		if (rows > 0)
        {
            return success();
        }
        return error();
	}
	
	/**
	 * 文件上传
	 */
	public boolean upload(OfficialEvolve officialEvolve, MultipartFile file, String type){
		boolean success = false;
		try {
			File document = null;
			String fileName = file.getOriginalFilename();  
			File firstFolder = new File(type);
			File secondFolder = new File(firstFolder + "/" + DateUtils.getDate() + "/" + officialEvolve.getConferenceId());
			if(!firstFolder.exists()){
				firstFolder.mkdirs();
			}
			if(!secondFolder.exists()){
				secondFolder.mkdirs();
			}
			document = new File(secondFolder+"/",fileName);
			System.out.println("文件上传路径"+ document);
	        file.transferTo(document); 
	        success = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return success;
	}
	
	/**
	 * id集合转化name集合
	 */
	public List<OfficialEvolve> idToNameList(List<OfficialEvolve> list){
		for(OfficialEvolve c: list){
			String proposerList = c.getPrepareList();
			String successList = c.getSuccessList();
			String failList = c.getFailList();
			String proposerName = "";//存放决议姓名名单
			String successName = "";//存放决议通过姓名名单
			String failName = "";//存放决议未通过姓名名单
			Conference conference = conferenceService.selectConferenceById(c.getConferenceId());
			c.setConference(conference);
			//构造决议姓名名单
			if(proposerList == null){
				c.setPrepareNameList(null);
			}else{
				String[] pList = proposerList.split(",");
				for(String id : pList){
					User user = userService.selectUserById(Long.valueOf(id));
					proposerName += user.getUserName() + ",";
				}
				c.setPrepareNameList(proposerName.substring(0, proposerName.length() - 2));
			}
			
			//构造未通过姓名名单
			if(failList == null){
				c.setFailNameList(null);
			}else{
				String[] fList = failList.split(",");
				for(String id : fList){
					User user = userService.selectUserById(Long.valueOf(id));
					failName += user.getUserName() + ",";
				}
				c.setFailNameList(failName.substring(0, failName.length() - 2));
			}
			
			//构造通过姓名名单
			if(successList == null){
				c.setSuccessNameList(null);
			}else{
				String[] sList = successList.split(",");
				for(String id : sList){
					User user = userService.selectUserById(Long.valueOf(id));
					successName += user.getUserName() + ",";
				}
				c.setSuccessNameList(successName.substring(0, successName.length() - 2));
			}
			
		}
		return list;
	}
	
}
